package cn.t212.cloud.zuul;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * zuul中的过滤器与javax.servlet中的不一样
 * 某个过滤器不执行，其他的过滤器默认会继续执行，
 * 而servelt中的过滤器是后续的过滤器不执行
 */
public class IpFilter extends ZuulFilter {
    private List<String> blackIpList = Arrays.asList("127.0.0.1");
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        System.out.println(context.getRequest().getRemoteHost());
        String ip = context.getRequest().getRemoteAddr();
        System.out.println("ip:" + ip);
        if(blackIpList.contains(ip)) {
            context.setSendZuulResponse(false);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map = new HashMap<>();
            map.put("403","非法访问");
            try {
                context.setResponseBody(objectMapper.writeValueAsString(map));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            context.getResponse().setContentType("application/json;charset=utf-8");
        }
        return null;
    }
}
